<template>
  <div>
    <Sheader :title="'地址管理'"></Sheader>
    <van-address-list
      v-model="chosenAddressId"
      :list="list"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      @select="select"
    />
  </div>
</template>

<script>
import Sheader from "../components/Header.vue";
import { reactive, toRefs, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getAddressList } from "../service/address";
export default {
  components: {
    Sheader,
  },
  setup() {
    const router = useRouter()
    const route = useRoute();
    const state = reactive({
      chosenAddressId: "1",
      list: [],
      from: route.query.from || "" 
    });

    onMounted(async () => {
      const { data } = await getAddressList();
      console.log(data);
      state.list = data.map((item) => {
        return {
          id: item.addressId,
          name: item.userName,
          tel: item.userPhone,
          address: `${item.provinceName} ${item.cityName} ${item.regionName} ${item.detailAddress}`,
          isDefault: !!item.defaultFlag,
        };
      });
    //   选中的地址
       state.chosenAddressId = Number(route.query.id)
    //   console.log(state.chosenAddressId);
    });

    const onAdd = () => {
      router.push({path: '/addressEdit',  query: {type: 'add', from: state.from}})
    }
    const onEdit = (item) => {
      console.log(item);

      router.push({path: '/addressEdit', query: {type: 'edit', addressId: item.id, from: state.from}})
    }
    const select = (item) => {
      router.push({path: '/order', query: { addressId: item.id, from: state.from }})
    }
    return {
      ...toRefs(state),
      onAdd,
      onEdit,
      select
    };
  },
};
</script>

<style>
</style>